package com.wans.guli.ware.service.impl;

import cn.hutool.core.util.StrUtil;
import com.wans.guli.common.utils.R;
import com.wans.guli.ware.feign.MemberFeignClient;
import com.wans.guli.ware.vo.FareVo;
import com.wans.guli.ware.vo.MemberAddressVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wans.guli.common.utils.PageUtils;
import com.wans.guli.common.utils.Query;

import com.wans.guli.ware.dao.WareInfoDao;
import com.wans.guli.ware.entity.WareInfoEntity;
import com.wans.guli.ware.service.WareInfoService;


@Service("wareInfoService")
public class WareInfoServiceImpl extends ServiceImpl<WareInfoDao, WareInfoEntity> implements WareInfoService {

    @Autowired
    private MemberFeignClient memberFeignClient;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        String key = (String) params.get("key");
        boolean notEmpty = StrUtil.isNotEmpty(key);

        IPage<WareInfoEntity> page = this.page(
                new Query<WareInfoEntity>().getPage(params),
                new QueryWrapper<WareInfoEntity>().lambda()
                        .like(notEmpty, WareInfoEntity::getName, key)
                        .or()
                        .like(notEmpty, WareInfoEntity::getAddress, key)
        );

        return new PageUtils(page);
    }

    /**
     * 计算运费
     *
     * @param addrId
     * @return
     */
    @Override
    public R getFare(Long addrId) {

        FareVo fareVo;

        //收获地址的详细信息
        R addrInfo = memberFeignClient.addressByAddrId(addrId);

        MemberAddressVo memberAddressVo = addrInfo.getData(MemberAddressVo.class);

        if (memberAddressVo != null) {
            String phone = memberAddressVo.getPhone();
            //截取用户手机号码最后一位作为我们的运费计算
            //1558022051
            String fare = phone.substring(phone.length() - 1);
            BigDecimal bigDecimal = new BigDecimal(fare);

            fareVo = FareVo.builder()
                    .address(memberAddressVo)
                    .fare(bigDecimal)
                    .build();

            return R.ok().put("data", fareVo);
        }
        return null;
    }
}